package com.fanghuaiming.notify.account.scheduled;

import com.fanghuaiming.notify.account.common.NotifyAccountCache;
import com.fanghuaiming.notify.account.service.NotityAccountInfoService;
import com.fanghuaiming.notify.account.spi.pay.NotifyPayFeignClient;
import com.fanghuaiming.notify.common.model.common.NotifyAccountChange;
import com.fanghuaiming.notify.common.model.pay.NotifyPay;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/****
 * @description: 定时读取本地处理失败的事务
 * @version:1.0.0
 * @author fanghuaiming
 * @data Created in 2020/12/3 下午6:06
 *
 */
@Component
@Slf4j
public class TryBestDealtransactionsIdScheduled {

    /**
     * 充值微服务spi
     */
    @SuppressWarnings("all")
    @Autowired
    private NotifyPayFeignClient notifyPayFeignClient;

    /**
     * 账户服务
     */
    @Autowired
    private NotityAccountInfoService notityAccountInfoService;


    /**
     * @Description: 定时每分钟处理异常失败事务
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/12/3 下午6:22
     * @version:1.0.0
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void ClearUserCardScheduled() {
        log.info("====== 定时失败事务处理器 检查当前是否有失败事务 ======");
        if(!NotifyAccountCache.transactionIdMap.isEmpty()){
            log.info("====== 定时失败事务处理器 当前有失败事务未完成,共有 {} 条失败事务 ======",NotifyAccountCache.transactionIdMap.size());
            //深拷贝
            HashMap<String, AtomicInteger> map = deepCopyMap(NotifyAccountCache.transactionIdMap);
            //业务处理
            map.forEach((transactionId,times) ->{
                if(times.get() >= 1){
                    try {
                        //处理已经失败设置的次数的数据
                        NotifyPay notifyPay = notifyPayFeignClient.payresult(transactionId);
                        log.info("======定时失败事务处理器 当前失败事务数据:{} ======",notifyPay);
                        //完成失败事务
                        notityAccountInfoService.dealErrorTransactionAccountBalance(NotifyAccountChange
                                .builder()
                                .transactionId(transactionId)
                                .accountNo(notifyPay.getAccountNo())
                                .amount(notifyPay.getPayAmount())
                                .build());
                        log.info("======定时失败事务处理器 处理失败事务完成 ======");
                        //事务处理完成就清除失败业务
                        NotifyAccountCache.transactionIdMap.remove(transactionId);
                    } catch (Exception e) {
                        log.info("======定时失败事务处理器 ribbon的loadbalance也许会失败 处理失败事务失败,等待下一分钟的失败事务补偿 ======");
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * @Description: 深拷贝对象
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/12/3 下午6:40
     * @version:1.0.0
     */
    private HashMap deepCopyMap(Map<String, AtomicInteger> transactionIdMap) {
        HashMap<String, AtomicInteger> map = new HashMap();
        Iterator it = transactionIdMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String key = (String) entry.getKey();
            map.put(key, transactionIdMap.get(key) != null ? transactionIdMap.get(key) : new AtomicInteger(0));
        }
        return map;
    }
}
